/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swe.chums.beans;

import com.swe.chums.dao.FeedbackDao;
import com.swe.chums.dao.UserDao;
import com.swe.chums.dao.exceptions.FeedbackDaoException;
import com.swe.chums.dao.exceptions.UserDaoException;
import com.swe.chums.dao.factory.DaoFactory;
import com.swe.chums.dao.model.Feedback;
import com.swe.chums.dao.model.FeedbackPk;
import com.swe.chums.utils.CommonUtils;
import com.swe.chums.utils.UserActivityTypeEnum;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.data.FilterEvent;

/**
 *
 * @author cilingir
 */
@ManagedBean(name = "feedbackBean")
@ViewScoped
public class FeedbackBean implements Serializable{
    
    private static Logger log = Logger.getLogger(FeedbackBean.class);
    private ArrayList<Feedback> myFeedbacks,allFeedbacks;
    private Feedback newFeedback, toBeRemovedFeedback;
    
    public FeedbackBean() {
        myFeedbacks = retrieveMyFeedbacks();
        allFeedbacks = retrieveAllFeedbacks();
    }

   
    /**
     * Get My Feedbacks
     * 
     * @return 
     */
    public ArrayList<Feedback> retrieveMyFeedbacks() {
        log.debug("[FeedbackBean.retrieveMyFeedbacks] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        myFeedbacks = new ArrayList<Feedback>();
        try {
            LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
            if (loginBean != null && loginBean.isIsUser()) {
                myFeedbacks = (ArrayList<Feedback>) DaoFactory.createFeedbackDao().findWhereUserIDEquals(loginBean.getUser().getId());
                
                for (int i=0; i<myFeedbacks.size(); i++) {
                    myFeedbacks.get(i).setUserText(loginBean.getUser().getName());
                }
            }
        } catch (FeedbackDaoException ex) {
            log.error("[FeedbackBean.retrieveMyFeedbacks] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return myFeedbacks;
    }
    
    /**
     * Get all feedbacks
     * 
     * @return 
     */
    public ArrayList<Feedback> retrieveAllFeedbacks() {
        log.debug("[FeedbackBean.retrieveAllFeedbacks] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        allFeedbacks = new ArrayList<Feedback>();
        try {
            LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
            if (loginBean != null && loginBean.isIsAdmin()) {
                
                UserDao userDao = DaoFactory.createUserDao();
                
                allFeedbacks = (ArrayList<Feedback>) DaoFactory.createFeedbackDao().findAll();
                
                for (int i=0; i<allFeedbacks.size(); i++) {
                    allFeedbacks.get(i).setUserText(userDao.findWhereIdEquals(allFeedbacks.get(i).getUserID()).get(0).getName());
                }
            }
        } catch (UserDaoException ex) {
            log.error("[FeedbackBean.retrieveAllActivities] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        } catch (FeedbackDaoException ex) {
            log.error("[FeedbackBean.retrieveAllFeedbacks] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allFeedbacks;
    }
    
    /**
     * Add feedback
     * 
     */
    public void addFeedback() {
        log.debug("[FeedbackBean.addFeedback] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (newFeedback.getText() != null && !newFeedback.getText().equals("")) {
                newFeedback.setText(newFeedback.getText().trim());
            } else {
                newFeedback.setText("");
            }
            
            if (newFeedback.getText().equals("")) {
                log.error("[FeedbackBean.addFeedback] - text is empty");
                text = "Text is empty";
                context.addMessage("formGiveFeedback:content", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(newFeedback.getText(), 240)) {
                log.error("[FeedbackBean.addFeedback] - text is not in allowed length: " + newFeedback.getText());
                text = "Content can't be longer than 240 characters";
                context.addMessage("formGiveFeedback:content", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[FeedbackBean.addFeedback] - there are errors with the form");
                
            } else {
                log.info("[FeedbackBean.addFeedback] - adding user: " + newFeedback.getText());

                LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
            
                Feedback feedback = new Feedback();
                
                feedback.setText(newFeedback.getText());
                feedback.setProcessed(0);
                feedback.setDate(new Date());
                feedback.setUserID(loginBean.getUser().getId());
                feedback.setUserText(loginBean.getUser().getName());
                
                CommonUtils.recordUserAction(loginBean.getUser().getId(), UserActivityTypeEnum.FEEDBACK, 0, newFeedback.getText());
                
                myFeedbacks.add(feedback);
                allFeedbacks.add(feedback);
                // Insert user
                DaoFactory.createFeedbackDao().insert(feedback);
                log.info("[FeedbackBean.addFeedback] - feedback inserted to db: " + newFeedback.getText());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
            }
            
        } catch (Exception ex) {
            log.error("[FeedbackBean.addFeedback] - General exception, message is:  " + ex.getMessage());
            context.addMessage("formGiveFeedback", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            
        }
    }
    
    /**
     * Remove feedback
     * 
     */
    public void removeFeedback() {
        log.debug("[FeedbackBean.removeFeedback] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        if (toBeRemovedFeedback != null) {
            
            FeedbackDao dao = DaoFactory.createFeedbackDao();
            FeedbackPk feedbackPk = new FeedbackPk();
            int id = toBeRemovedFeedback.getId();
            feedbackPk.setId(id);
            try {
                
                dao.delete(feedbackPk);
                
                allFeedbacks.remove(toBeRemovedFeedback);
                myFeedbacks.remove(toBeRemovedFeedback);
                
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Succesfully removed"));

            } catch (FeedbackDaoException ex) {
                log.error("[FeedbackBean.removeFeedback] - error while deleting values from DB, message is:  " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
            }
            
        } else {
            // You shouldnt be here!
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "No source selected"));
        }
    }
    
    
    /**
     * Filter event handler
     *
     * @param event
     * @return
     */
    public Map<String, String> onFilter(FilterEvent event) {

        log.debug("[AdminBean.onFilterAllWebResources] started");
        Map<String, String> filters;
        DataTable table = (DataTable) event.getSource();

//        List<User> obj = table.getFilteredData();
//        if (obj != null) {
//            table.getFilteredData().remove(obj);
//        }
        filters = table.getFilters();
        filters.clear();

        return filters;
    }
    
    
    /*----Getter Setters---- */

    public ArrayList<Feedback> getMyFeedbacks() {
        return myFeedbacks;
    }

    public void setMyFeedbacks(ArrayList<Feedback> myFeedbacks) {
        this.myFeedbacks = myFeedbacks;
    }

    public ArrayList<Feedback> getAllFeedbacks() {
        return allFeedbacks;
    }

    public void setAllFeedbacks(ArrayList<Feedback> allFeedbacks) {
        this.allFeedbacks = allFeedbacks;
    }

    public Feedback getNewFeedback() {
        if (newFeedback == null) {
            newFeedback = new Feedback();
        }
        return newFeedback;
    }

    public void setNewFeedback(Feedback newFeedback) {
        this.newFeedback = newFeedback;
    }

    public Feedback getToBeRemovedFeedback() {
        return toBeRemovedFeedback;
    }

    public void setToBeRemovedFeedback(Feedback toBeRemovedFeedback) {
        this.toBeRemovedFeedback = toBeRemovedFeedback;
    }
    
    
    
   
}
